﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Core;
using Spring.Context;
using Spring.Context.Support;
using System.Configuration;

namespace ShopSpace.Infrastructure.UI
{
	/// <summary>
	/// Allows UI layer to get references to
	/// the configured implementations of service interfaces
	/// (e.g. Repositories, etc.)
	/// </summary>
	/// <remarks>
	/// Normally, Spring will inject any services the UI object
	/// depends on.  This class exists for cases where the UI
	/// object cannot be (pratically) managed by Spring.
	/// </remarks>
	public static class ServiceLocator
	{
		/// <summary>
		/// Returns an implementation of <typeparamref name="T"/>
		/// </summary>
		public static T Get<T>()
			where T : class
		{
			IApplicationContext springContext = ContextRegistry.GetContext();
			Type serviceType = typeof(T);
			string key = serviceType.Name;
			if (!springContext.ContainsObject(key))
			{
				throw new Exception("No key " + key + " configured");
			}
			object service = springContext.GetObject(key, serviceType);
			if (service == null)
			{
				throw new Exception("object found for " + key + " did not match type " + serviceType.Name);
			}
			return service as T;
		}
	}
}